<%--suppress BadExpressionStatementJS --%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + " ://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<jsp:include page="head.jsp"/>
<link rel="stylesheet" href="<%=path%>/layui/css/layui.css">
<link href="<%=path%>/css/bootstrap.min.css" rel="stylesheet">
<!-- Bootstrap -->
<script src="<%=path%>/layer/layer.js"></script>
<script src="<%=path%>/layui/layui.all.js"></script>
<script src="<%=path%>/js/bootstrap.min.js"></script>
<!-- 引入样式 -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- 引入组件库 -->
<!-- 先引入 Vue -->
<script src="//unpkg.com/vue/dist/vue.js"></script>
<script src="//unpkg.com/element-ui@2.0.11/lib/index.js"></script>

<style type="text/css">

    .page div {
        padding: 10px 15px;
        border: 1px solid #EAEAEA;
        border-radius: 2px;
        font-size: 12px;
        display: inline-block;
        position: absolute;
        left: 50%;
    }

    body {
        position: relative;
        margin-top: -50px;
    }

    .addBox {
        position: absolute;
        top: 50px;
        width: 100%;
        left: 0;
    }

    span.tag {
        font-size: 18px;
        margin-right: 6px;
        color: red;
    }

    .container {
        margin-bottom: 65px;
    }

    div.layui-laydate .layui-this {
        background-color: #0080ff !important;
        color: #fff !important;
    }

    input[type=file].el-upload__input {
        display: none;
    }

    .el-upload--picture-card, .el-upload-list--picture-card .el-upload-list__item {
        width: 162px;
        height: 162px;
    }

    .el-dialog {
        margin: 0 auto;
        width: 80%;
    }

    #app {
        text-align: center;
        margin: 10px 0 15px;
    }

    .el-upload-list--picture-card .el-upload-list__item-status-label {
        right: -18px;
        top: -12px;
        width: 45px;
        height: 30px;
    }

    [class^=el-icon-] {
        line-height: unset;
    }

    .namebox {
        width: 24%;
        display: inline-block;
        position: absolute;
        right: -15px;
        top: 18px;
    }

    .addressbtn {
        position: absolute;
        right: 0;
        margin: 29.5px 0 0;
        background-color: transparent;
        padding: 0;
        width: 20%;
        border: 1px solid rgba(0, 0, 0, .22);
        height: 40px;
        border-radius: 3px;
        border-bottom-left-radius: 0;
        border-top-left-radius: 0;
        background: #f2f2f2;
        color: #999;
    }

    #place {
        border-right: none;
        border-bottom-right-radius: 0;
        border-top-right-radius: 0;
        width: 80%;
    }
</style>
</head>

<body>
<div class="addBox" style="">
    <!--后端从这里开始改-->
    <div class="container">
        <h2 class="maintitle">发布信息</h2>
        <form id="uploadForm" onsubmit="return check()" action="javascript:;" method="POST" name="formlostfound"
              enctype="multipart/form-data">
            <!--选择信息类别-->
            <div class="form-group">
                <div class="form-inline">
                    <label for="mes-type">信息类别：&nbsp;&nbsp;&nbsp;</label>
                    <select class="form-control" id="mes-type" name="lost_found">
                        <option value="1" selected="selected">遗失信息</option>
                        <option value="2">招领信息</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <div class="form-inline">
                    <label for="thing-type">物品类别：&nbsp;&nbsp;&nbsp;</label>
                    <select class="form-control" id="thing-type" name="class">
                        <option value="1">证件</option>
                        <option value="2">书本</option>
                        <option value="3">财物</option>
                        <option value="4">数码</option>
                        <option value="5">其他</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label for="title"><span class="tag">*</span>标题：&nbsp;&nbsp;&nbsp;</label>
                <input type="text" name="title" id="title" class="form-control" placeholder="信息标题..." maxlength="20"
                       required="required">
            </div>
            <div class="layui-inline" style="display: block;">
                <label for="time"><span class="tag">*</span>时间：&nbsp;&nbsp;&nbsp;</label>
                <div class="layui-input-inline" style="width: 100%;">
                    <input type="text" class="layui-input" id="time" placeholder="时间..." readonly>
                    <input type="text" name="" id="timetest" style="display: none;">
                </div>
            </div>
            <div class="form-group" style="position:relative;">
                <label for="contacter">联系人（不填则使用真名）：&nbsp;&nbsp;&nbsp;</label>
                <input type="text" name="contacter" id="contacter" style="width: 77%;" class="form-control"
                       placeholder="联系人（不填则使用真名）..."
                       required="required">
                <div class="namebox">
                    <div class="noname" style="color: #999;margin-left: -6px;">是否匿名</div>
                    <div class="mui-switch mui-switch-blue mui-switch-mini">
                        <div class="mui-switch-handle"></div>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label for="tel"><span class="tag">*</span>手机：&nbsp;&nbsp;&nbsp;</label>
                <input type="text" name="tel" id="tel" class="form-control" placeholder="手机号码..." maxlength="11"
                       required="required">
            </div>
            <div class="form-group addressgroup" style="position:relative;">
                <div class="layui-btn  layui-btn-primary addressbtn">查看地图</div>
                <label for="place"><span class="tag">*</span>地点：&nbsp;&nbsp;&nbsp;</label>
                <input type="text" name="place" id="place" class="form-control" placeholder="地点..."
                       required="required"/>
            </div>
            <div class="form-group">
                <label for="detail"><span class="tag">*</span>详情描述：&nbsp;&nbsp;&nbsp;</label>
                <textarea class="form-control" name="detail" id="detail" rows="6" placeholder="详情描述..." maxlength="200"
                          required="required"></textarea>
            </div>
            <div class="form-group">
                <label for="short">短号：&nbsp;&nbsp;&nbsp;</label>
                <input type="text" name="short" id="short" class="form-control" placeholder="短号 (非必填)..."
                       maxlength="11">
            </div>
            <div class="form-group">
                <label for="qq">QQ：&nbsp;&nbsp;&nbsp;</label>
                <input type="text" name="qq" id="qq" class="form-control" placeholder="QQ号码 (非必填)..." maxlength="10">
            </div>
            <label for="place">图片上传(&nbsp;最多6张&nbsp;)：&nbsp;&nbsp;&nbsp;</label>


            <div id="app">
                <el-upload action="<%=path%>/file/uploadImgs"
                           list-type="picture-card"
                           ref="upload"
                           name="files"
                           :on-success="uploadSuccess"
                           :on-error="uploadError"
                           :before-upload="beforeAvatarUpload"
                           :on-preview="handlePictureCardPreview"
                           :on-remove="handleRemove">
                    <i class="el-icon-plus"></i>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible" size="tiny">
                    <img width="100%" :src="dialogImageUrl" alt>
                </el-dialog>
            </div>
            <div class="fileList" style="display: none;"></div>

            <button type="button" onclick="return check()" style="padding: 12px 30px; width: 100%; font-size: 16px;"
                    class="btn btn-info">提交
            </button>
        </form>
    </div>
</div>
<div class="tabs">
    <div class="tab tabActive">
        <span class="mui-icon mui-icon-compose index_tab"></span>
        <div class="tabText tabtext_out">发布信息</div>
    </div>
    <div class="tab">
        <span class="mui-icon mui-icon-home"></span>
        <div class="tabText">首页</div>
    </div>
    <div class="tab">
        <span class="mui-icon mui-icon-person"></span>
        <div class="tabText">个人中心</div>
    </div>
</div>
<script src="<%=path%>/js/mui.min.js"></script>
<script>
    /*
     *
     *  *************** 调用js桥方法 ***************
     *
     * */

    $('.addressbtn').click(function () {
        // 获取地址
        XuntongJSBridge.call('getCurrentPosition', {}, function (result) {
            if (result.success === "true") {
                $("#place").val(result.data.detailAddress);
            } else {
                layer.msg("获取失败请手动输入", {icon: 5, time: 600});
            }
        });
    });

    var selfUser;
    // 存储当前用户
    XuntongJSBridge.call('getPersonInfo', {}, function (result) {
        if (result.success === "true") {
            selfUser = result.data;
            $('#contacter').val(selfUser.name);
        }
    });

</script>
<script type="text/javascript">
    /*
    * 文件上传
    * */
    urls = "";
    var Main = {
        data() {
            return {
                dialogImageUrl: '',
                dialogVisible: false
            };
        },
        methods: {
            uploadSuccess(response, file, fileList) {
                if (response.result == "success") {
                    urls = urls + response.data.urls;
                    $('.fileList').text(urls);
                } else {
                    this.$message.error('未知错误，上传失败！');
                }
            },
            uploadError(response, file, fileList) {
                this.$message.error('上传失败，请检查网络！');
            },
            handleRemove(file, fileList) {
            },
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            beforeAvatarUpload(file) {
                let supportedTypes = ['image/jpg', 'image/jpeg', 'image/png', 'image/bmp', 'image/gif'];
                flag = true;
                const isLt2M = file.size / 1024 / 1024 < 4;

                if (supportedTypes.indexOf(file.type) <= 0) {
                    this.$message.error('上传头像图片只能是JPG、JPEG、PNG、BMP、GIF格式!');
                    flag = false;
                }

                if (!isLt2M) {
                    this.$message.error('上传图片大小不能超过 4MB!');
                }
                return flag && isLt2M;
            }
        }
    }
    var Ctor = Vue.extend(Main);
    new Ctor().$mount('#app');
</script>
<script>
    layui.use(['layer', 'form', 'laydate'], function () {
        var laydate = layui.laydate,
            layer = layui.layer;
        var form = layui.form;
        laydate.render({
            elem: '#time'
            , type: 'datetime'
        });
    });

    $(function () {
        /*tab标签*/
        var $tab = $('.tab');
        var $tabText = $('.tabText');
        $tab.click(function () {
            var index = $(this).index();
            $(this).addClass("tabActive").siblings().removeClass("tabActive");
            $(this).children("span").addClass("index_tab").parent().siblings().children("span").removeClass("index_tab");
            $(this).children($tabText).addClass("textActive tabtext_out").parent().siblings().children($tabText).removeClass("textActive tabtext_out");
            if (index === 0) {
                window.location.href = "<%=path%>/add"
            } else if (index == 1) {
                window.location.href = "<%=path%>/index"
            } else {
                window.location.href = "<%=path%>/person"
            }
        });
    });
</script>
<script>
    var $uls = $('.el-upload-list>li');
    var checkdate = $('#time'),
        checktel = $("#tel"),
        checktitle = $("#title"),
        checkplace = $("#place"),
        checkcontacter = $("#contacter"),
        checkdetails = $("#detail");
    var imgs = new Array();
    var conFlag = false;

    mui('.mui-switch').each(function () {
        /**
         * toggle 事件监听
         */
        this.addEventListener('toggle', function (event) {
            var conFlag = event.detail.isActive;
            if (conFlag) {
                $('#contacter').val("");
                $('#contacter').attr("placeholder", "");
                $('#contacter').attr("readonly", "readonly");
            } else {
                $('#contacter').attr("readonly", false);
                $('#contacter').attr("placeholder", "联系人（不填则使用真名）");
            }
        });
    });

    /*
     * 验证表单
     * */
    function isNull(str) {
        if (str == "") return true;
        var regu = "^[ ]+$";
        var re = new RegExp(regu);
        return re.test(str);
    }

    function msg(msg) {
        layer.msg(msg, {time: 800});
    }

    // 校验中文英文姓名
    function checkName(s) {
        var pattern = /^[a-zA-Z\u4e00-\u9fa5 ]{1,8}$/;
        if (!pattern.exec(s)) return false;
        return true
    }

    // 校验手机号码
    function checkIsMobil(s) {
        var pattern = /^1[34578]\d{9}$/;
        if (!pattern.exec(s)) return false;
        return true
    }

    // 校验短号
    function checkShort(s) {
        var pattern = /^[0-9]{3,8}$/;
        if (!pattern.exec(s)) {
            return false;
        }
        return true;
    }

    // 校验qq
    function checkQQ(s) {
        var pattern = /^[1-9][0-9]{4,12}$/;
        if (!pattern.exec(s)) return false;
        return true
    }

    function trimS(s) {
        return s.replace(/(^\s*)|(\s*$)/g, "");
    }

    /*提交按钮*/
    function check() {
        $uls.each(function () {
            imgs.push($(this).children("img").attr("src"));
        });

        function checkLen(obj, l1, l2, ms) {
            var lv = obj.val();
            lv = trimS(lv);
            if (lv.length < l1 || lv.length > l2) {
                msg(ms);
                obj.focus();
                return false;
            }
            return true;
        }

        if (isNull(checktitle.val())) {
            msg("标题不能为空");
            checktitle.focus();
            return false;
        }

        if (!checkLen(checktitle, 4, 32, "标题长度为4-32")) {
            return false;
        }
        if (isNull(checkdate.val())) {
            msg("您还未选日期");
            $('#timetest').focus();
            return false;
        }
        if (conFlag) {
            if (!isNull(checkcontacter.val())) {
                if (!checkLen(checkcontacter, 2, 8, "联系人长度为2-8")) {
                    return false;
                }
                if (!checkName(checkcontacter.val())) {
                    msg("联系人只能输入中英文和空格");
                    checkcontacter.focus();
                    return false;
                }
            }
        }

        if (isNull(checktel.val())) {
            msg("手机不能为空");
            checktel.focus();
            return false;
        }
        if (checktel.val().length !== 11) {
            msg("手机号码必须是11位");
            checktel.focus();
            return false;
        }
        if (!checkIsMobil(checktel.val())) {
            msg("手机号码格式错误");
            checktel.focus();
            return false;
        }

        if (isNull(checkplace.val())) {
            msg("地点不能为空");
            checkplace.focus();
            return false;
        }
        if (!checkLen(checkplace, 4, 64, "地点长度为4-64")) {
            return false;
        }

        if (isNull(checkdetails.val())) {
            msg("详情不能为空");
            checkdetails.focus();
            return false;
        }
        if (!checkLen(checkdetails, 4, 128, "详情长度为4-128")) {
            return false;
        }

        var shortv1 = $("#short").val();
        if (!isNull(shortv1)) {
            if (!checkLen($("#short"), 3, 8, "短号长度为3-8")) {
                return false;
            }
            if (!checkShort(shortv1)) {
                msg("短号格式错误");
                $("#short").focus();
                return false;
            }
        }

        if (!isNull($("#qq").val())) {
            if (!checkLen($("#qq"), 4, 12, "QQ长度为4-12")) {
                return false;
            }
            if (!checkQQ($("#qq").val())) {
                msg("qq格式错误");
                $("#qq").focus();
                return false;
            }
        }

        var checkdatev = $('#time').val(),
            checktelv = $("#tel").val(),
            checktitlev = $("#title").val(),
            checkplacev = $("#place").val(),
            checkcontacterv = $("#contacter").val(),
            checkdetailsv = $("#detail").val(),
            qqv = $("#qq").val(),
            shortv = $("#short").val();
        var mes = $("#mes-type option:selected").val();
        var thing = $("#thing-type option:selected").val();

        checkcontacterv = trimS(checkcontacterv);
        if (checkcontacterv.length == 0) {
            checkcontacterv = "";
        } else if (conFlag) {
            checkcontacterv = " ";
        }

        layer.confirm('确认提交吗?', {
            btn: ['确认', '取消'] //按钮
        }, function () {
            var imgaeList = $('.fileList').text();

            layer.load(2);
            $.ajax({
                //这里是地址
                url: '<%=path%>/message/save',
                type: 'post',
                dataType: 'json',
                data: {
                    "title": checktitlev,
                    "type": mes,
                    "time": checkdatev,
                    "address": checkplacev,
                    "thing": thing,
                    "detail": checkdetailsv,
                    "linkphone": checktelv,
                    "linkman": checkcontacterv,
                    "linkshort": shortv,
                    "images": imgaeList,
                    "qq": qqv
                },
                success: function (data) {
                    layer.closeAll("loading");
                    if (data.result === "faild") {
                        if (data.cause === "no login error") {
                            layer.msg('请先登录智慧校园云平台', {icon: 5, time: 600});
                            setTimeout(function () {
                                XuntongJSBridge.call('close');
                            }, 700);
                        } else {
                            window.location.href = "<%=path%>/error";
                        }
                    } else {
                        layer.msg('添加成功', {icon: 6, time: 600});
                        setTimeout(function () {
                            window.location.href = "<%=path%>/index"
                        }, 700);
                    }
                },
                error: function (data) {
                    layer.closeAll("loading");
                    layer.msg('请检查网络', {icon: 5, time: 600});
                }
            })
        }, function () {

        });
    }
</script>
</body>

</html>